/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.community.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.Messages;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Comment;
import etcore.webapp.grouptalk.common.object.Directory;
import etcore.webapp.grouptalk.common.object.Group;
import etcore.webapp.grouptalk.common.object.Message;
import etcore.webapp.grouptalk.common.object.MessageTags;
import etcore.webapp.grouptalk.common.object.Tag;
import etcore.webapp.grouptalk.common.object.TagContainer;
import etcore.webapp.grouptalk.common.object.Topic;
import etcore.webapp.grouptalk.common.service.DirectoryService;
import etcore.webapp.grouptalk.common.service.GroupService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.common.service.MessageTagsService;
import etcore.webapp.grouptalk.common.service.TagContainerService;
import etcore.webapp.grouptalk.common.service.TagService;
import etcore.webapp.grouptalk.common.service.TopicService;
import etcore.webapp.grouptalk.user.object.Member;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.MemberService;
import etcore.webapp.grouptalk.util.DateUtil;
import etcore.webapp.grouptalk.util.StringDisplay;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of showing a
 * community group detail,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class CommunityViewAction extends AbstractAction {

	private static final long serialVersionUID = 2646436091736321681L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;

	// parameter/attributes constants

	public static final String KEY = "key";
	public static final String CURRENT_GROUP = "currentGroup";

	public static final String NAME_TAG = "name&tag";
	public static final String COMMENT_NUM = "commentNum";
	public static final String LAST_COMMENT = "lastComment";
	public static final String RESTRICTED = "restricted";
	// utility constants

	public static final String CMD_VALUE = "addGmessage";
	public static final String MINUS_ONE = "-1";

	public static final String ADD_FOCUS = "addFocus";
	public static final String DEL_FOCUS = "delFocus";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {
		boolean included = true, restricted = false;
		String gid = request.getParameter(PageConstants.GID);
		Group group = null;
		GroupService groupService = new GroupService();
		if (gid != null) {
			group = groupService.findById(new Integer(gid));

			if (group != null && group.getOpen() == 2) {
				boolean isAdmin = (Boolean) request
						.getAttribute(PageConstants.ISADMIN);
				if (group.getFunc() == 1 && !isAdmin)
					restricted = true;

				request.setAttribute(CURRENT_GROUP, group);
				HttpSession session = request.getSession(true);
				User user = (User) session
						.getAttribute(PageConstants.SESSIONUSER);
				if (user != null && user.getIsLock() != 1) {
					MemberService memberService = new MemberService();
					Member member = memberService.findByUsernameAndGid(
							user.getUserName(), new Integer(gid));
					if (member == null)
						included = false;
					else {
						if (member.getLocked() == 0)
							restricted = false;
						request.setAttribute("member", member);
					}
				}
				request.setAttribute("included", included);
				request.setAttribute("restricted", restricted);
				return ACCESS_ALLOWED;
			}
		}

		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;
		return PageConstants.PAGE_PATH_COMMUNITYVIEW;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		Group group = (Group) request.getAttribute(CURRENT_GROUP);
		if (group == null)
			return;
		boolean restricted = (Boolean) request.getAttribute("restricted");

		addFocus(request);
		removeFocus(request);
		getFocus(request);
		if (!restricted) {

			getTagContainers(request);
			addGmessage(request);
			TopicService topicService = new TopicService();

			if (group.getNav() == 1)
				request.setAttribute(PageConstants.NAV, PageConstants.ONE);
			DirectoryService directoryService = new DirectoryService();
			List<Directory> targetDirectories = directoryService
					.findByGid(group.getId());
			if (targetDirectories != null && targetDirectories.size() > 0) {
				Directory directory = (Directory) targetDirectories.get(0);

				request.setAttribute("currentDirectory", directory);

			}
			List<Topic> topics = topicService.findByProperty(PageConstants.GID,
					group.getId());
			request.setAttribute(PageConstants.TOPICS, topics);
			Map topicMap = new HashMap();
			for (Topic topic : topics) {
				topicMap.put(topic.getId(), topic.getName());
			}
			request.setAttribute(PageConstants.TOPIC_MAP, topicMap);
			getTagContainers(request);
			getMessages(request);
		} else {
			HttpSession session = request.getSession(true);
			String msg = null;
			String lang = (String) session.getAttribute(Messages.LANG);
			if (lang != null && lang.equals(Messages.LANG_EN)) {
				msg = Messages.getELabel(Messages.ERROR_MSG);
			} else {
				msg = Messages.getLabel(Messages.ERROR_MSG);
			}
			request.setAttribute(PageConstants.MSG, msg);
		}

	}

	private void addFocus(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (ADD_FOCUS.equals(cmd)) {
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
			if (user == null || user.getIsLock() == 1)
				return;
			if (user != null) {
				String gid = request.getParameter(PageConstants.GID);
				if (gid == null)
					return;
				MemberService memberService = new MemberService();
				boolean included = (Boolean) request.getAttribute("included");
				if (!included) {
					Group group = (Group) request.getAttribute(CURRENT_GROUP);
					if (group == null)
						return;
					Member member = new Member();
					member.setGid(new Integer(gid));
					member.setMytype(Member.MEMBER);
					if(group.getFunc()==1)member.setLocked(1);
					member.setUserName(user.getUserName());

					memberService.save(member);

					request.setAttribute("included", true);
					String msg = null;
					String lang = (String) session.getAttribute(Messages.LANG);
					if (lang != null && lang.equals(Messages.LANG_EN)) {
						msg = Messages.getELabel(Messages.MSG_SUCCESS);
					} else {
						msg = Messages.getLabel(Messages.MSG_SUCCESS);
					}
					request.setAttribute(PageConstants.MSG, msg);

				}
			}
		}
	}

	private void getFocus(HttpServletRequest request) {

		MemberService memberService = new MemberService();
		String gid = request.getParameter(PageConstants.GID);
		long memberCount = memberService.getAllMemberNum(new Integer(gid));
		request.setAttribute("memberCount", memberCount);

	}

	private void getTagContainers(HttpServletRequest request) {
		TagContainerService tagContainerService = new TagContainerService();

		String gid = request.getParameter(PageConstants.GID);
		List<TagContainer> tagContainers = tagContainerService.findByProperty(
				PageConstants.GID, new Integer(gid));
		if (tagContainers != null) {
			request.setAttribute(PageConstants.TAGCONTAINERS, tagContainers);
			request.setAttribute(PageConstants.TAGCONTAINERCOUNT,
					tagContainers.size());
			TagService tagService = new TagService();
			for (TagContainer tagContainer : tagContainers) {

				List<Tag> tags = tagService.findByProperty(
						PageConstants.TAGCONTAINERID, tagContainer.getId());
				if (tags != null) {
					request.setAttribute(tagContainer.getId()
							+ PageConstants.TAGS, tags);
					request.setAttribute(tagContainer.getId()
							+ PageConstants.TAGCOUNT, tags.size());
				}
			}

		}
	}

	private void removeFocus(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (DEL_FOCUS.equals(cmd)) {
			HttpSession session = request.getSession(true);
			User user = (User) session.getAttribute(PageConstants.SESSIONUSER);
			if (user == null || user.getIsLock() == 1)
				return;
			if (user != null) {
				String gid = request.getParameter(PageConstants.GID);
				if (gid == null)
					return;
				MemberService memberService = new MemberService();
				boolean included = (Boolean) request.getAttribute("included");
				if (included) {
					Member member = memberService.findByUsernameAndGid(
							user.getUserName(), new Integer(gid));
					if (!member.getMytype().equals(Member.OWNER))
						memberService.deleteSingle(member);

					request.setAttribute("included", false);
					String msg = null;
					String lang = (String) session.getAttribute(Messages.LANG);
					if (lang != null && lang.equals(Messages.LANG_EN)) {
						msg = Messages.getELabel(Messages.MSG_SUCCESS);
					} else {
						msg = Messages.getLabel(Messages.MSG_SUCCESS);
					}
					request.setAttribute(PageConstants.MSG, msg);

				}
			}
		}
	}

	private void addGmessage(HttpServletRequest request) {
		String cmd = request.getParameter(PageConstants.CMD);
		if (CMD_VALUE.equals(cmd)) {
			try {

				HttpSession session = request.getSession(true);
				User user = (User) session
						.getAttribute(PageConstants.SESSIONUSER);
				if (user == null || user.getIsLock() == 1)
					return;
				if (user != null) {
					String name = request.getParameter(PageConstants.NAME);
					String tid = request.getParameter(PageConstants.TID);
					String content = request
							.getParameter(PageConstants.CONTENT);
					if (tid != null && !tid.equals(MINUS_ONE) && user != null
							&& name != null) {

						Message message = new Message();
						MessageService messageService = new MessageService();

						message.setName(name);

						message.setTid(new Integer(tid));
						message.setFlag(new Integer(0));
						if (content != null) {

							message.setContent(StringDisplay
									.secureOutput(content));

						}

						message.setUp(new Integer(0));
						message.setAddtime(DateUtil.getTime(Config.getProperty(Config.HOURS_DIFFERENCE)));
						message.setNum(new Integer(0));
						message.setUserName(user.getUserName());
						messageService.save(message);

						@SuppressWarnings("unchecked")
						List<TagContainer> tagContainers = (List<TagContainer>) request
								.getAttribute(PageConstants.TAGCONTAINERS);
						if (tagContainers != null && tagContainers.size() > 0) {
							MessageTagsService messageTagsService = new MessageTagsService();

							for (TagContainer tagContainer : tagContainers) {
								String param = PageConstants.TAGCONTAINERID
										+ tagContainer.getId();
								String[] tagIds = request
										.getParameterValues(param);
								if (tagIds != null && tagIds.length > 0) {
									for (String tagId : tagIds) {
										if (tagId != null
												&& !Symbols.BLANK.equals(tagId)
												&& !MINUS_ONE.equals(tagId)) {
											MessageTags messageTags = new MessageTags();
											messageTags.setTagid(new Integer(
													tagId));
											messageTags.setMid(message.getId());
											messageTagsService
													.save(messageTags);
										}
									}
								}
							}
						}
						String msg = null;
						String lang = (String) session
								.getAttribute(Messages.LANG);
						if (lang != null && lang.equals(Messages.LANG_EN)) {
							msg = Messages.getELabel(Messages.MSG_SUCCESS);
						} else {
							msg = Messages.getLabel(Messages.MSG_SUCCESS);
						}
						request.setAttribute(PageConstants.MSG, msg);
					}
				}

			} catch (Exception ex) {
				ex.printStackTrace();
			}

		}
	}

	/*
	 * Integer tempm_id=(Integer)tempm[0]; Integer tempm_tid=(Integer)tempm[1];
	 * String tempm_name=(String)tempm[2]; String *
	 * tempm_addtime=(String)tempm[3]; String tempm_userName=(String)tempm[4];
	 * Integer tempm_num=(Integer)tempm[5]; Integer tempm_up=(Integer)tempm[6];
	 * Integer tempm_flag=(Integer)tempm[7]; String tempm_tag=(String)tempm[8];
	 * String tempm_source=(String)tempm[9]; String
	 * tempm_stime=(String)tempm[10]; Integer
	 * commentNum=gmessdao.findCommentNum(tempm_id); Gcomment
	 * tmpG=gmessdao.findLastComment(tempm_id);
	 */

	@SuppressWarnings("unchecked")
	private void getMessages(HttpServletRequest request) {
		int intpageid = 1;
		MessageService msgService = new MessageService();
		String gid = request.getParameter(PageConstants.GID);
		String tid = request.getParameter(PageConstants.TID);
		String key = request.getParameter(KEY);
		List<String> tagList = new ArrayList<String>();
		List<TagContainer> tagContainers = (List<TagContainer>) request
				.getAttribute(PageConstants.TAGCONTAINERS);
		if (tagContainers != null && tagContainers.size() > 0) {

			for (TagContainer tagContainer : tagContainers) {
				String param = PageConstants.TAGCONTAINERID
						+ tagContainer.getId();
				String tagId = request.getParameter(param);
				if (tagId != null && !Symbols.BLANK.equals(tagId)
						&& !"-1".equals(tagId)) {
					tagList.add(tagId);

				}
			}
		}
		int unit = 15;
		@SuppressWarnings("rawtypes")
		List msgs = null;
		long all = 0;
		int begin = 0, pagenums = 0;
		String pageid = request.getParameter(PageConstants.PAGEID);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		if (tid != null && !tid.equals(Symbols.BLANK)) {

			if (key != null && !key.equals(Symbols.BLANK)) {
				all = msgService.searchSizeByPropertyAndTid(PageConstants.NAME,
						key, new Integer(tid));
				pagenums = (int) ((all + unit - 1) / unit);
				begin = unit * (intpageid - 1);
				msgs = msgService.searchByPropertyAndTid(PageConstants.NAME,
						key, new Integer(tid), begin, unit);
			} else if (tagList.size() > 0) {
				all = msgService.findSizeByPropertyAndTags(PageConstants.TID,
						new Integer(tid), tagList);
				pagenums = (int) ((all + unit - 1) / unit);
				begin = unit * (intpageid - 1);
				msgs = msgService.findByPropertyAndTags(PageConstants.TID,
						new Integer(tid), tagList, begin, unit);
			} else {
				all = msgService.findSizeByProperty(PageConstants.TID,
						new Integer(tid));
				pagenums = (int) ((all + unit - 1) / unit);
				begin = unit * (intpageid - 1);
				msgs = msgService.findByProperty(PageConstants.TID,
						new Integer(tid), begin, unit);
			}

		} else {
			if (gid != null) {
				if (key != null && !key.equals(Symbols.BLANK)) {
					all = msgService.searchSizeByPropertyAndGid(
							PageConstants.NAME, key, new Integer(gid));
					pagenums = (int) ((all + unit - 1) / unit);
					begin = unit * (intpageid - 1);
					msgs = msgService.searchByPropertyAndGid(
							PageConstants.NAME, key, new Integer(gid), begin,
							unit);
				} else if (tagList.size() > 0) {
					all = msgService.findSizeByGidAndTags(new Integer(gid),
							tagList);
					pagenums = (int) ((all + unit - 1) / unit);
					begin = unit * (intpageid - 1);
					msgs = msgService.findMsgsByGidAndTags(new Integer(gid),
							tagList, begin, unit);
				} else {
					all = msgService.findSizeByGid(new Integer(gid));
					pagenums = (int) ((all + unit - 1) / unit);
					begin = unit * (intpageid - 1);
					msgs = msgService.findMsgsByGid(new Integer(gid), begin,
							unit);
				}
			}
		}

		int startpid = intpageid - 3;
		if (startpid <= 0)
			startpid = 1;
		int endpid = intpageid + 8;
		if (intpageid > 8)
			endpid = intpageid + 6;
		if (endpid >= pagenums)
			endpid = pagenums;

		request.setAttribute(PageConstants.START_PID, startpid);
		request.setAttribute(PageConstants.END_PID, endpid);

		// comment count and time
		for (int k = 0; k < msgs.size(); k++) {
			Object[] tempm = (Object[]) msgs.get(k);
			Integer tempm_id = (Integer) tempm[0];
			Long commentNum = msgService.findCommentNum(tempm_id);
			Comment tmpG = msgService.findLastComment(tempm_id);
			request.setAttribute(tempm_id + COMMENT_NUM, commentNum);
			if (tmpG != null)
				request.setAttribute(tempm_id + LAST_COMMENT, tmpG.getTime());
		}

		request.setAttribute(PageConstants.INTPAGEID, intpageid);
		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute(PageConstants.MSGS, msgs);

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return null;
	}

}
